package com.whc.gulimall.ware.config;

import com.whc.gulimall.ware.constant.WareMQConstant;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * RabbitMQ延时消息队列配置
 *
 * @author angaoen
 */
@Configuration
public class MyMQConfig {
    /**
     * 延时队列
     *
     * @return Queue
     */
    @Bean
    public Queue stockDelayQueue() {
        // String name, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments
        Map<String, Object> arguments = new HashMap<>(3);
        arguments.put("x-dead-letter-exchange", WareMQConstant.STOCK_EVENT_EXCHANGE);
        arguments.put("x-dead-letter-routing-key", "stock.release");
        // 消息过期时间 2分钟
        arguments.put("x-message-ttl", 120000);
        return new Queue(WareMQConstant.STOCK_DELAY_QUEUE, true, false, false, arguments);
    }

    /**
     * 处理队列
     *
     * @return Queue
     */
    @Bean
    public Queue orderReleaseOrderQueue() {
        // String name, boolean durable, boolean exclusive, boolean autoDelete
        return new Queue(WareMQConstant.STOCK_RELEASE_STOCK_QUEUE, true, false, false);
    }

    /**
     * 交换机
     *
     * @return Exchange
     */
    @Bean
    public Exchange stockEventExchange() {
        // String name, boolean durable, boolean autoDelete
        return new TopicExchange(WareMQConstant.STOCK_EVENT_EXCHANGE, true, false);
    }

    @Bean
    public Binding stockReleaseBinding() {
        /*
        String destination, DestinationType destinationType, String exchange, String routingKey,
			Map<String, Object> arguments
         */
        return new Binding(WareMQConstant.STOCK_RELEASE_STOCK_QUEUE, Binding.DestinationType.QUEUE,
                // 路由key一般为事件名
                WareMQConstant.STOCK_EVENT_EXCHANGE, "stock.release.#", null);
    }

    @Bean
    public Binding stockLockedBinding() {
        /*
        String destination, DestinationType destinationType, String exchange, String routingKey,
			Map<String, Object> arguments
         */
        return new Binding(WareMQConstant.STOCK_DELAY_QUEUE, Binding.DestinationType.QUEUE,
                // 路由key一般为事件名
                WareMQConstant.STOCK_EVENT_EXCHANGE, "stock.locked", null);
    }
}
